define(function (require, exports, module) {
    require("apps/pbom/page.css");
    require("apps/easyui");
    exports.init = function (ctx, uuid, config) {
        var page = new $.PageDomFactory(uuid);
        page.getJqDom("formDetail").find(".easyui-validatebox").validatebox();
        page.getJqDom("next").linkbutton({
            onClick: function () {
                var baseForm = page.getJqDom("baseForm");
                if (!baseForm.form("validate")) {
                    return;
                }
                $("body").wait("start", "工艺结构保存中，请稍后！");
                var postData = baseForm.serializeJson();
                $.post(ctx + "/app/api/pbom/addTop", postData, function (data) {
                    $("body").wait("end");
                    if ($.isPlainObject(data) && data.error) {
                        $.messager.alert('信息',
                            data.msg, 'info');
                    } else {
                        window.location.href = ctx + "/app/api/pbom/toEdit?id=" + data.id
                    }
                }, "JSON");
            }
        });
        page.getJqDom("cancel").linkbutton({
            onClick: function () {
                window.location.href = ctx + "/app/api/pbom/index"
            }
        });
        page.getJqDom("bomType").combobox({
            value:config.bomType
        });
        var pp = page.getJqDom("code");
        var cache = {};
        page.getJqDom("pName").on("change", function(){
            var v = $(this).val();
            if(!pp.val().length){
                if(cache[v]){
                    pp.val(cache[v]);
                }else{
                    $.post(ctx + "/app/api/pbom/createCode", {pName:v}, function(data){
                        cache[v] = data.code;
                        pp.val(data.code);
                    }, "JSON")
                }
            }
        });
        page.getJqDom("number").numberbox({
            min:1
        });
        function toSave(publish) {
            //获取提交的参数值
            var pbom = page.getJqDom("baseForm").serializeJson();
            pbom.children = page.getJqDom("grid").treegrid("getData");
            //遍历构造节点
            deepSet(pbom);
            pbom.publish = publish;
            $("body").wait("start", "结构数据保存中，请稍后！");
            $.post(ctx + "/app/api/pbom/save", $.utils.buildJson(pbom), function (data) {
                $("body").wait("end");
                if ($.isPlainObject(data) && data.error) {
                    $.messager.alert('信息',
                        data.msg, 'info');
                } else {
                    $.messager.alert('信息',
                        "保存成功！", 'info');
                    window.location.href = ctx + "/app/api/pbom/index";
                }
            }, "JSON");
        }

        page.getJqDom("save").linkbutton({
            onClick: function () {
                toSave(true);
            }
        });

        function deepSet(pbom) {
            var children = pbom.children;
            delete pbom.children;
            if(pbom.refId){
                pbom.id = pbom.refId;
            }
            if (!children || !children.length) {
                return;
            }
            pbom.tpBomRelations = [];
            for (var i = 0, l = children.length; i < l; i++) {
                if (children[i].type == 'add') {
                    delete children[i].id;
                }
                pbom.tpBomRelations.push({child: children[i], number: children[i].number});
                deepSet(children[i]);
            }
        }

        page.getJqDom("saveDraft").linkbutton({
            onClick: function () {
                toSave(false);
            }
        });
        //保存页面
        if (page.getJqDom("grid").length) {
            require("apps/grid");

            var pageListComponent = new $.PageTreeListComponent(uuid, {
                pagination: false,
                view: {
                    grid: "grid",
                    myToolbar: "news_tb",
                    colbar: "user_list_btn"
                },
                configs: {
                    gridTitle: "工艺设计结构列表",
                    gridUrl: null,
                    idField: "id",
                    treeField: "pName",
                    gridColumns: [
                        {
                            field: 'id',
                            checkbox: true
                        },
                        {
                            field: 'temp1',
                            hidden: true
                        },
                        {
                            field: 'pName',
                            title: '名称',
                            width: 100,
                            align: 'left'
                        },
                        {
                            field: 'code',
                            title: '编码',
                            width: 100,
                            align: 'left'
                        },
                        {
                            field: 'number',
                            title: '数量（件）',
                            width: 50,
                            align: 'left'
                        },
                        {
                            field: 'bomType',
                            title: '制造分类',
                            width: 100,
                            align: 'left'
                        },
                        {
                            field: 'remark',
                            title: '备注',
                            hidden: true,
                            width: 50,
                            align: 'left'
                        },
                        {
                            field: 'status',
                            title: '状态',
                            width: 50,
                            align: 'left',
                            formatter: function (value, row, index) {
                                if (value == "PUBLISH") {
                                    return "已发布";
                                } else if (value == "UN_PUBLISH") {
                                    return "未发布";
                                } else {
                                    return "已废弃";
                                }
                            }
                        }
                    ],
                    onExpand:function(row){
                        if(row.children == undefined){
                            pageListComponent.grid.treegrid("loadChildren", {
                                url:ctx + "/app/api/pbom/children",
                                row:row
                            });
                        }
                    }
                },
                events: {
                    renderColBarBefore: function (key, row) {
                        if (key == "moveUp") {
                            return this.grid.treegrid("getPrev", row.id);
                        } else if (key == "moveDown") {
                            return this.grid.treegrid("getNext", row.id);
                        } else if (key == "moveIn") {
                            var prev = this.grid.treegrid("getPrev", row.id);
                            return prev && prev.status == "UN_PUBLISH";
                        } else if (key == "moveOut") {
                            var p = this.grid.treegrid("getParent", row.id);
                            return p && p.status == "UN_PUBLISH";
                        } else if (key == "remove") {
                            var p = this.grid.treegrid("getParent", row.id);
                            return !p || p.status == "UN_PUBLISH";
                        }
                        return true;
                    },
                    onClickColBtn: function (context, btn, row) {
                        switch (btn.key) {
                            case "view":
                                whenView(context, row);
                                break;
                            case "moveUp":
                                whenMove(context, row, "up");
                                break;
                            case "moveOut":
                                whenMove(context, row, "out");
                                break;
                            case "moveIn":
                                whenMove(context, row, "in");
                                break;
                            case "moveDown":
                                whenMove(context, row, "down");
                                break;
                            case "remove":
                                whenRemove(context, row);
                                break;
                            default :
                                break;
                        }
                    },
                    onClickToolbarBtn: function (context, btn) {
                        switch (btn.key) {
                            case "add":
                                whenAdd(context, btn.href);
                                break;
                            case "choose":
                                whenChoose(context, btn.href);
                                break;
                            default :
                                break;
                        }
                    }
                }
            });

            var topId = page.getJqDom("id").val();

            $.getJSON(ctx + "/app/api/pbom/children?id=" + topId, function (data) {
                pageListComponent.grid.treegrid("loadData", data);
            });
            var globalWindow = new $.PageWindow();

            function whenAdd(context) {
                globalWindow.create({
                    href: ctx + "/app/api/pbom/addSingle",
                    method: "add_pbom_child",
                    title: "新增结构",
                    callback: function (status, postData) {
                        if (status) {
                            postData.id = $.utils.createUUID(10);
                            postData.type = "add";
                            postData.status = "UN_PUBLISH";
                            var data = context.grid.treegrid("getData");
                            data.push(postData);
                            context.grid.treegrid("loadData", data);
                        }
                    }
                });
                globalWindow.open();
            }


            function whenChoose(context, href) {
                globalWindow.create({
                    href: ctx + "/app/api/pbom/choose",
                    method: "choose_pbom_child",
                    title: "选择已发布的结构",
                    width: 1000,
                    callback: function (status, postData) {
                        if (status) {
                            //检查同级是否包含结构
                            var items = context.grid.treegrid("getData");
                            var newData = [];
                            for (var j = 0, ll = postData.length; j < ll; j++) {
                                var find = false;
                                for (var i = 0, l = items.length; i < l; i++) {
                                    if (items[i].id == postData[j].id) {
                                        var number = parseInt(items[i].number);
                                        number += parseInt(postData[j].number);
                                        items[i].number = number;
                                        find = true;
                                        break;
                                    }
                                }
                                if (!find) {
                                    newData.push(postData[j]);
                                }
                            }
                            items = items.concat(newData);
                            //检查不同级，重设部分id
                            setNewId([], items);

                            context.grid.treegrid("loadData", items);
                        }
                    }
                });
                globalWindow.open();
            }

            function setNewId(ids, pboms){
                 for(var i= 0; i < pboms.length; i++){
                     if(ids.contains(pboms[i].id)){
                         pboms[i] = $.extend({}, pboms[i], true);
                         pboms[i].refId = pboms[i].id;
                         pboms[i].id = $.utils.createUUID(10);
                     }else{
                         ids.push(pboms[i].id)
                     }
                     if(pboms[i].children){
                         setNewId(ids, pboms[i].children);
                     }
                 }
            }

            function whenRemove(context, row) {
                context.grid.treegrid("pop", row.id);
                context.grid.treegrid("reload");
            }

            function whenMove(context, row, direct) {
                var parent = context.grid.treegrid("getParent", row.id);
                if (direct == "up") {
                    var prev = context.grid.treegrid("getPrev", row.id);
                    if (prev) {
                        context.grid.treegrid("pop", row.id);
                        context.grid.treegrid("insert", {
                            before: prev.id,
                            data: row
                        });
                    }
                } else if (direct == "down") {
                    var next = context.grid.treegrid("getNext", row.id);
                    if (next) {
                        context.grid.treegrid("pop", row.id);
                        context.grid.treegrid("insert", {
                            after: next.id,
                            data: row
                        });
                    }
                } else if (direct == "out") {
                    if (parent) {
                        context.grid.treegrid("pop", row.id);
                        context.grid.treegrid("insert", {
                            after: parent.id,
                            data: row
                        });
                    }
                } else if (direct == "in") {
                    var prev = context.grid.treegrid("getPrev", row.id);
                    if (prev) {
                        context.grid.treegrid("pop", row.id);
                        context.grid.treegrid("append", {
                            parent: prev.id,
                            data: [row]
                        });
                    }
                }
                var data = context.grid.treegrid("getData");
                context.grid.treegrid("loadData", data);
            }

            function whenView(context, row) {
                context.detail("工艺设计结构详情查看", row);
            }
        }
    }
});